package com.cms.work.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>Title: SystemExceptionResolver</p>
 * <p>Description: 全局异常处理</p>
 * <p>Email: yuyue_qty@163.com</p>
 * @author 晴天雨
 * @date 2016年11月22日下午8:52:40
 * @version 1.0
 */
public class SystemExceptionResolver implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(SystemExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView result = null;
		SystemException exception = null;
		if(ex instanceof SystemException){
			exception = (SystemException) ex;
			if(exception.getCodeEnum().getLabel().equals("user")){
				result = new ModelAndView("login");
			}else{
				result = new ModelAndView("error");
			}
		}
		result.addObject("msg", ex.getMessage());
		logger.info("SystemExceptionResolver err msg:"+ex.getMessage());
		return result;
	}
	
	
	//前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中，如果遇到异常就会执行此方法
	//handler最终要执行的Handler，它的真实身份是HandlerMethod
	//Exception ex就是接收到异常信息
//	@Override
//	public ModelAndView resolveException(HttpServletRequest request,
//			HttpServletResponse response, Object handler, Exception ex) {
//		//输出异常
//		ex.printStackTrace();
//		
//		//统一异常处理代码
//		//针对系统自定义的CustomException异常，就可以直接从异常类中获取异常信息，将异常处理在错误页面展示
//		//异常信息
//		String message = null;
//		CustomException customException = null;
//		//如果ex是系统 自定义的异常，直接取出异常信息
//		if(ex instanceof CustomException){
//			customException = (CustomException)ex;
//		}else if(ex instanceof UnauthorizedException){
//			customException = new CustomException("无权访问资源");
//		}else if(ex instanceof MaxUploadSizeExceededException){
//			customException = new CustomException("文件超过最大限制");
//		}else{
//			//针对非CustomException异常，对这类重新构造成一个CustomException，异常信息为“未知错误”
//			customException = new CustomException("未知错误");
//		}
//		
//		//错误 信息
//		message = customException.getMessage();
//		
//		request.setAttribute("message", message);
//
//		
//		try {
//			//转向到错误 页面
//			request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request, response);
//		} catch (ServletException e) {
//			logger.error(e.getMessage(), e);
//		} catch (IOException e) {
//			logger.error(e.getMessage(), e);
//		}
//		
//		return new ModelAndView();
//	}
	
}
